package com.chaos.framework.starter.config;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class MybaitsPlusTenantFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化方法，可以在这里进行一些初始化操作
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String tenantIdStr = httpRequest.getHeader("X-Tenant-Id"); // 假设请求头中的键为 "X-Tenant-Id"
        Long tenantId = null;

        if (tenantIdStr != null && !tenantIdStr.isEmpty()) {
            try {
                tenantId = Long.parseLong(tenantIdStr);
            } catch (NumberFormatException e) {
                // 处理转换失败的情况
                throw new ServletException("Invalid tenant ID format", e);
            }
        }

        MybaitsPlusTenantContextHolder.setCurrentTenantId(tenantId);

        try {
            chain.doFilter(request, response);
        } finally {
            MybaitsPlusTenantContextHolder.clear(); // 清除线程局部变量，避免内存泄漏
        }
    }

    @Override
    public void destroy() {
        // 销毁方法，可以在这里进行一些清理操作
    }
}
